package com.jysz.certificate.service.system;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

 
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import com.jysz.certificate.persistence.dao.system.TreatyDao;   
import com.jysz.certificate.persistence.enums.mytask.Prwarningtype;
import com.jysz.certificate.persistence.model.cm.Certification;
import com.jysz.certificate.persistence.model.mytask.Prewarning;
import com.jysz.certificate.persistence.model.system.Financial;
import com.jysz.certificate.persistence.model.system.Shop;
import com.jysz.certificate.persistence.model.system.Treaty;
import com.jysz.certificate.utils.DateUtil;
import com.jysz.webcore.ssh.orm.hibernate.support.Page;
import com.jysz.webcore.ssh.service.EntityService;

 
@Service
public class TreatyService extends EntityService<Treaty, Long, TreatyDao>{
	@Resource
	private TreatyDao treatyDao;
	@Resource
	private FinancialService financialService;
	@Override
	public TreatyDao getEntityDao() {
		return treatyDao;
	}
	
	public void save(Treaty treaty){
		if(treaty.getUnitPrice()==null)
			treaty.setUnitPrice(0d);
		treatyDao.saveTreaty(treaty);
	}
	
	public Page<Treaty> selectAll(int pageNo, int pageSize){
		return this.findPage(treatyDao.createCriteria(), pageNo, pageSize);
	}
	public List<Treaty> treatieList(Long id){
		return treatyDao.treatyList(id,"0");
	}
	public Page<Treaty> selectTR(Treaty search ,int pageNo, int pageSize,Double floorsD,Double floorsX){
		Criteria criteria = treatyDao.createCriteria();
		criteria.addOrder(Order.desc("updatedAt"));
		Criteria shopCriteria = criteria.createCriteria(Treaty.COLUMN_SHOP);
		if(search != null  ){
			if(search.getShop() !=null && StringUtils.isNotBlank(search.getShop().getShopName())){
				shopCriteria.add(Restrictions.like(Shop.COLUMN_SHOP_NAME,  search.getShop().getShopName(), MatchMode.ANYWHERE));
			}
			if(search.getShop() !=null && StringUtils.isNotBlank(search.getShop().getShopMark())){
				shopCriteria.add(Restrictions.like(Shop.COLUMN_SHOP_MARK,  search.getShop().getShopMark(), MatchMode.ANYWHERE));
			}
			if(StringUtils.isNotBlank(search.getBranch())){
				criteria.add(Restrictions.like(Treaty.COLUMN_BRANCH, search.getBranch(), MatchMode.ANYWHERE));
			}
		
			if(StringUtils.isNotBlank(search.getIdentifier())){
				criteria.add(Restrictions.eq(Treaty.COLUMN_IDENTIFIER, search.getIdentifier()));
			} 
			
			if(search.getCollectionWay()!=null && StringUtils.isNotBlank(search.getCollectionWay()) ){
				criteria.add(Restrictions.eq(Treaty.COLUMN_COLLECTION_WAY, search.getCollectionWay()));
			}
			if(search.getMark() != null ){
				criteria.add(Restrictions.eq("mark", search.getMark()));
			}
			if(search.getFinancial() != null && search.getFinancial().getId() != null ){
				System.out.println(search.getFinancial().getId());
				criteria.createCriteria("financial").add(Restrictions.eq("id", search.getFinancial().getId()));
			}
		}
		if(floorsX!=null){
			if(floorsX!=0){
				criteria.add(Restrictions.le(Treaty.COLUMN_FLOORS,floorsX));
			}
		}
		if(floorsD!=null){
			if(floorsD!=0 && floorsD!=null){
				criteria.add(Restrictions.ge(Treaty.COLUMN_FLOORS,floorsD));
			}
		}
		treatyDao.addShopCriteria(shopCriteria,true,null);
		return this.findPage(criteria, pageNo, pageSize);
	}
	
	/**
	 * 根据店铺、金融机构获得协议
	 * @author xuxiaolong
	 * @param finId
	 * @param shopId
	 * @return
	 */
	public Treaty find(Long finId,Long shopId){
		Criteria criteria = treatyDao.createCriteria();
		criteria.createCriteria("shop").add(Restrictions.eq("id", shopId));
		criteria.createCriteria("financial").add(Restrictions.eq("id", finId));
		criteria.add(Restrictions.eq("state", true));
		return (Treaty) criteria.uniqueResult();
	}
	
	public Treaty shopNameKey(String identifier){
		return treatyDao.shopNameKey(identifier);
	}
	public List<Prewarning> prewarnings(boolean bool){
		List<Prewarning> prewarnings = new ArrayList<Prewarning>();
		SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
		Criteria criteria = treatyDao.createCriteria();
		if(bool){
			criteria.add(Restrictions.between("endDate",new Date(), DateUtil.addDays(new Date(), 14)));
		}else{
			criteria.add(Restrictions.le("endDate", new Date()));
		}
		criteria.add(Restrictions.eq("state", true));
		treatyDao.addShopCriteria(criteria,false,null);//添加数据过滤
		List<Treaty> treaties = criteria.list();
		for(int i=0;i<treaties.size();i++){
			String msg ="";
			Treaty treaty = treaties.get(i);
			Prewarning prewarning = new Prewarning();
			
				if(bool){//没有超过
					prewarning.setBool(false);
					msg = treaty.getShop().getShopName()+"  与   "+treaty.getFinancial().getName()+"  的协议  "+dft.format(treaty.getEndDate())+"  到期，协议编号为："+treaty.getIdentifier();
				}else{//超过
					msg = treaty.getShop().getShopName()+"  与   "+treaty.getFinancial().getName()+"  的协议 已到期，协议编号为："+treaty.getIdentifier();
					prewarning.setBool(true);
				}
			prewarning.setPrwarningtype(Prwarningtype.TREATY);
			prewarning.setMsg(msg);
			prewarning.setUrlAddress("/system/treaty/index.do");
			prewarnings.add(prewarning);
		}
		return prewarnings;
		
	}
	/**
	 * 是否存在 协议
	 * @return
	 */
	public boolean whetherThere(Long shopId,Long fianId,Date benginDate,Long id){
		Criteria criteria = treatyDao.createCriteria();
		criteria.createCriteria("shop").add(Restrictions.eq("id", shopId));
		criteria.createCriteria("financial").add(Restrictions.eq("id", fianId));
		criteria.add(Restrictions.eq("state", true));
		criteria.add(Restrictions.ge("endDate",benginDate));
		List<Treaty> treaties = criteria.list();
		if(treaties.size()>0){
			if(treaties.size() == 1){
				Treaty treaty = treaties.get(0);
				if(id!=null && treaty.getId() == id){
					return false;
				}
			}
			return true;
		}
		return false;
	}
	public List<Treaty> whetherTheres(Long shopId,Long fianId,Date benginDate){
		Criteria criteria = treatyDao.createCriteria();
		criteria.createCriteria("shop").add(Restrictions.eq("id", shopId));
		criteria.createCriteria("financial").add(Restrictions.eq("id", fianId));
		criteria.add(Restrictions.eq("state", true));
		criteria.add(Restrictions.ge("endDate",benginDate));
		List<Treaty> treaties = criteria.list();
		return treaties;
	}
	
	/**
	 * 根据店铺找金融机构
	 */
	public List<Financial> getFinanList(Long shopId){
		Criteria criteria = treatyDao.createCriteria();
		List<Financial> list = new ArrayList<Financial>();
		criteria.add(Restrictions.eq("shop.id", shopId));
		List<Treaty> treatyList = criteria.list();
		if(treatyList!=null&&treatyList.size()>0){
			for (Iterator iterator = treatyList.iterator(); iterator.hasNext();) {
				Treaty treaty = (Treaty) iterator.next();
				Financial f = financialService.getFinancial(treaty.getFinancial().getId());
				if(!list.contains(f))
					list.add(f);
			}
		}
		return list;
	}
	
	/**
	 * 是否存在 协议
	 * @return
	 */
	public boolean whetherThere(Long shopId,Long fianId){
		Criteria criteria = treatyDao.createCriteria();
		criteria.createCriteria("shop").add(Restrictions.eq("id", shopId));
		criteria.createCriteria("financial").add(Restrictions.eq("id", fianId));
		List<Treaty> treaties = criteria.list();
		if(treaties.size()>0){
			return false;//
		}
		return true;
	}
	/**
	 * 查询生效的协议
	 * @param shopId
	 * @return
	 */
	public List<Treaty> treatyList(Long shopId){
		Criteria criteria = treatyDao.createCriteria();
		criteria.createCriteria("shop").add(Restrictions.eq("id", shopId));
		criteria.add(Restrictions.eq("state", true));
		return criteria.list();
	}
	/**
	 * 获取所有有效地协议
	 * @return
	 */
	public Map<String, Treaty> treatyAllMap(boolean bool){
		Map<String, Treaty> map = new HashMap<String, Treaty>();
		Criteria criteria = treatyDao.createCriteria();
		criteria.add(Restrictions.eq("state", true));
		criteria.add(Restrictions.ge("endDate", DateUtil.addDays(DateUtil.getSystemDate(),1)));
		List<Treaty> treaties = criteria.list();
		if(bool && treaties.size() >0){//这里使用的值为金融机构 
			for(Treaty treaty : treaties ){
				map.put(treaty.getShop().getShopName()+"-"+treaty.getFinancial().getName(), treaty);
			}
			return map;
		}else if(bool == false && treaties.size() >0){//这里使用的值为销售店 
			for(Treaty treaty : treaties ){
				map.put(treaty.getShop().getShopName(), treaty);
			}
			return map;
		}
		return null;
		
	}
	public Page<Treaty> sillPageTyeaty(Shop shop,Long fiamlId,int pageNo, int pageSize){
		Criteria criteria = treatyDao.createCriteria();
		criteria.add(Restrictions.eq(Treaty.COLUMN_STATE,  true));
		criteria.createCriteria(Treaty.COLUMN_SHOP).add(Restrictions.eq(Shop.COLUMN_TODELETE, 1));
		if(shop!=null){
			if(StringUtils.isNotBlank(shop.getShopName())){
				criteria.createCriteria(Treaty.COLUMN_SHOP).add(Restrictions.like(Shop.COLUMN_SHOP_NAME, shop.getShopName(), MatchMode.ANYWHERE));
			}
			if(StringUtils.isNotBlank(shop.getShopMark())){
				criteria.createCriteria(Treaty.COLUMN_SHOP).add(Restrictions.like(Shop.COLUMN_SHOP_MARK, shop.getShopMark(), MatchMode.START));
			}
		}
		if(null != fiamlId){
//			finalCriteria.createCriteria("").add(Restrictions.eq("id", financial));
			criteria.createCriteria("financial").add(Restrictions.eq("id", fiamlId));
		}
		criteria.add(Restrictions.ge("endDate", new Date()));
		criteria.add(Restrictions.eq("unitPrice", 0D));
		criteria.add(Restrictions.eq("collectionWay", "0"));
		return this.findPage(criteria, pageNo, pageSize);
	}

	
	public Map<String, Treaty> getTreatyAllMap(boolean bool){
		Map<String, Treaty> map = new HashMap<String, Treaty>();
		Criteria criteria = treatyDao.createCriteria();
		criteria.add(Restrictions.eq("state", true));
		criteria.add(Restrictions.ge("endDate", DateUtil.addDays(DateUtil.getSystemDate(),1)));
		List<Treaty> treaties = criteria.list();
		if(bool && treaties.size() >0){//这里使用的值为金融机构 
			for(Treaty treaty : treaties ){
//				map.put(treaty.getShop().getShopName()+"-"+treaty.getFinancial().getName(), treaty);
				map.put(treaty.getShop().getShopName()+"-"+treaty.getFinancial().getBrief(), treaty);
			}
			return map;
		}else if(bool == false && treaties.size() >0){//这里使用的值为销售店 
			for(Treaty treaty : treaties ){
				map.put(treaty.getShop().getShopName(), treaty);
			}
			return map;
		}
		return null;
		
	}
}
